package br.com.djiadreams.loginecadastro;

import br.com.djiadreams.georeferencedsignalproject.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class Cadastro extends Activity {
	private ProgressDialog progresso;
	private CadastroWebService cadastrar;
	private boolean sucesso;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cadastro);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.cadastro, menu);
		return true;
	}

	public void confirmar(View v) {
		String nome, senha, confirma;
		EditText n = (EditText) findViewById(R.id.cd_nome);
		EditText s = (EditText) findViewById(R.id.cd_senha);
		EditText cS = (EditText) findViewById(R.id.cd_confirm_senha);
		nome = n.getText().toString();
		senha = s.getText().toString();
		confirma = cS.getText().toString();

		if (!senha.equals(confirma) || senha.equals("") || confirma.equals("") || n.equals("")) {
			Toast.makeText(this, "Campos inv�lidos", Toast.LENGTH_LONG).show();
			s.setText(null);
			cS.setText(null);
			n.requestFocus();
			return;
		}

		DadosLogin entrar = new DadosLogin(nome, senha);
		progresso = ProgressDialog.show(this, "Cadastrando...",
				"Aguarde um instante.");
		cadastrar = new CadastroWebService();
		cadastrar.execute(entrar);
	}

	private class CadastroWebService extends
			AsyncTask<DadosLogin, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progresso.show();
		}

		@Override
		protected Boolean doInBackground(DadosLogin... params) {
			return cadastrando(params[0]);
		}

		private Boolean cadastrando(DadosLogin dadosLogin) {
			// TODO Auto-generated method stub
			Thread timer = new Thread() {
				@Override
				public void run() {
					try {
						sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
			timer.start();
			sucesso = true;
			return sucesso;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			progresso.dismiss();
			Toast.makeText(Cadastro.this, "Cadastro realizado",
					Toast.LENGTH_SHORT).show();
			finish();
		}
	}

}
